package com.pww.movie.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class FFmpegUtil {

    public static boolean convertToHLS(String ffmpegPath, String inputPath, String outputDir, String outputName) throws IOException, InterruptedException {
        File dir = new File(outputDir);
        if (!dir.exists()) dir.mkdirs();

        String outputM3U8 = outputDir + File.separator + outputName + ".m3u8";

        ProcessBuilder builder = new ProcessBuilder(
                ffmpegPath,
                "-i", inputPath,
                "-codec:v", "libx264",
                "-codec:a", "aac",
                "-strict", "-2",
                "-f", "hls",
                "-hls_time", "10",
                "-hls_list_size", "0",
                "-hls_segment_filename", outputDir + File.separator + outputName + "_%03d.ts",
                outputM3U8
        );

        builder.redirectErrorStream(true);
        Process process = builder.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }

        return process.waitFor() == 0;
    }
}

